<template>
  <div
    class="color-select-container"
    :style="{
      width: props.width ? `${props.width}px` : '100%',
      height: props.height ? `${props.height}px` : '100%',
      border: `1px solid ${themeStyle[theme].borderColor2}`,
      color: themeStyle[theme].textColor1
    }"
  >
    <div
      class="color-block-container"
      :style="{
        borderRight: `1px solid ${themeStyle[theme].borderColor1}`
      }"
    >
      <Popover placement="leftTop" :trigger="'click'" @open-change="popoverChange">
        <template #content>
          <Sketch v-model="sketchColor" />
        </template>
        <div
          class="color-block"
          :style="{ background: styleColor, border: `1px solid ${themeStyle[theme].borderColor1}` }"
        ></div>
      </Popover>

      <div
        v-if="disable"
        class="color-mark"
        @click="
          (e) => {
            e.stopPropagation()
          }
        "
      ></div>
    </div>

    <div class="color-input-container">
      <Input
        v-model:value="styleColor"
        type="text"
        size="small"
        :style="{ color: themeStyle[theme].textColor2 }"
        @input="colorChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { useStyleStore } from '@renderer/store/globalStyle/style'
import { storeToRefs } from 'pinia'
import { Input, Popover } from 'ant-design-vue'
import { ref, watch } from 'vue'
import { Sketch } from '@ckpack/vue-color'

const props = defineProps({
  color: {
    type: String,
    required: true
  },
  disable: Boolean,
  width: Number,
  height: Number
})

const styleColor = ref(props.color)
const sketchColor = ref<any>('')
const disable = ref(props.disable)
watch(
  () => props.disable,
  (val) => {
    disable.value = val
  }
)
watch(
  () => sketchColor.value?.hex8,
  (val) => {
    if (val) {
      styleColor.value = val
      colorChange()
    }
  }
)

const emit = defineEmits(['update:color', 'change'])

const globalStyleStore = useStyleStore()
const { theme, themeStyle } = storeToRefs(globalStyleStore)

const colorChange = () => {
  emit('update:color', styleColor.value)
  emit('change')
}

const popoverChange = (open: boolean) => {
  if (open) {
    sketchColor.value = styleColor.value
  }
}
</script>

<style scoped lang="scss">
.color-select-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: left;
  align-items: center;

  .color-block-container {
    width: 40px;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;

    .color-block {
      width: 25px;
      height: 12px;
      cursor: pointer;
    }
    .color-mark {
      position: absolute;
      width: 100%;
      height: 100%;
      cursor: not-allowed;
      background-color: #cccccc38;
    }
  }
  .color-input-container {
    width: calc(100% - 40px);
    height: 100%;
    input {
      border: none;
      outline: none;
    }
  }
}
</style>
